function formatRes(res) {
  let r = null
  try {
    r = JSON.parse(res)
  } catch (err) {
    r = res
  }
  return r
}

/**
 * linpengWS websocket类
 * @params opts { url, onopen, onclose, onmessage, onerror }
 */
class LindadayoWS {
    reconnectCodes = [1001, 1009, 1012, 1013]
    reconnectCount = 0
    opts: any
    wsocket: WebSocket

    constructor(opts) {
      this.opts = opts;
      this.init()
    }

    init() {
      window.WebSocket = window.WebSocket || (window as any).MozWebSocket;
      if (!window.WebSocket) throw new Error('Your browser does not support WebSocket');

      this.wsocket = new WebSocket(this.opts.url);

      ['onopen', 'onclose', 'onmessage', 'onerror'].forEach(ev => {
        this.wsocket[ev] = (e) => {
          if (ev === 'onmessage') {
            const res = formatRes(e.data)
            typeof this.opts[ev] === 'function' && this.opts[ev].call(this, res, e);
          } else if (ev === 'onclose') {
            if (this.reconnectCodes.includes(e.code) && this.reconnectCount < 10) {
              setTimeout(() => {
                this.reconnect()
              }, 2500)
            }
            typeof this.opts[ev] === 'function' && this.opts[ev].call(this, e);
          } else {
            typeof this.opts[ev] === 'function' && this.opts[ev].call(this, e);
          }
        }
      })
    }

    /**
     * send 发送 websocket 消息
     * @param 参数 message 为发消息的内容
     */
    send(message) {
      let p = message;
      if (!this.wsocket || this.wsocket.readyState !== WebSocket.OPEN) {
        console.log('ws连接尚未建立，暂不能发送消息');
        return;
      }
      if (typeof message === 'object' && message !== null) {
        p = JSON.stringify(message)
      }
      this.wsocket.send(p);
    }

    /**
     * close 关闭 websocket
     */
    close() {
      this.wsocket && this.wsocket.close();
    }

    /**
     * reconnect 重连 websocket
     */
    reconnect() {
      this.reconnectCount++;
      this.init();
    }
}

export default LindadayoWS
